package cn.teaseed.comn;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import cn.teaseed.view.HomeView;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
@Data
public class CorsParam {
    //DG-Lab 链接使用的服务端ID 暂时不做成支持多机互联
    public static String clientID;
    //VRChat OSC Server
    public static Integer VRChatListenerPort = 9001;
    //登陆用户位置
    public static String HomePath;
    //本地数据位置
    public static final String ConfigPath = "\\Documents\\\\TeaseedSoftware\\\\setting.json";
    //波形数据
    public static Map<String, List<String>> WaveMap = new HashMap<>();
    //A通道波形最高强度
    public static String WaveAStrengthMax = "20";
    //B通道波形最高强度
    public static String WaveBStrengthMax = "20";
    //创建一个1缓存容量的对象用于传输对象于不同的窗口切换
    public static final Cache<String, Object> fifoCache = CacheUtil.newFIFOCache(1);
    //强制设置的本地URL地址
    public static String manualURL;
    //当前连接设备
    public static String CurrentlyConnectedDevice = "NoDevice";
    //已连接的蓝牙设备列表 <DeviceName,DeviceMac>
    public static Map<String, String> BleDevice = new HashMap<>();
    //蓝牙设备配置表 <ConfigName,BleConfigEntity>
    public static Map<String, BleConfigEntity> BleConfig = new HashMap<>();
    //蓝牙设备关系对照表 <BleDeviceName,DeviceNameStart>
    public static Map<String, String> BleComp = new HashMap<>();

    static {
        clientID = UUID.randomUUID().toString();
        //获取当前登录信息
        Properties properties = System.getProperties();
        //登录路径
        HomePath = properties.get("user.home").toString();

        try {
            String dataJson = getDataJson();
            SettingEntity entity = JSONUtil.toBean(dataJson, JSONConfig.create(), SettingEntity.class);
            WaveMap = entity.getWaveMap();
            manualURL = entity.getManualURL();
            BleDevice = entity.getBleDevice();
            if (BleDevice == null) BleDevice = new HashMap<>();
            BleConfig = entity.getBleConfig();
            if (BleConfig == null) {
                Map<String, BleConfigEntity> bleConfig = new HashMap<>();
                bleConfig.put("HUAWEI", new BleConfigEntity("HUAWEI", true, 2, 1));
                bleConfig.put("Mi", new BleConfigEntity("Mi", true, 2, 0));
                BleConfig = bleConfig;
            }
            BleComp = entity.getBleComp();
            if (BleComp == null) BleComp = new HashMap<>();
        } catch (IOException e) {
            log.error("波形数据加载失败");
        }
    }

    public static void refreshWave() {
        try {
            String dataJson = getDataJson();
            SettingEntity entity = JSONUtil.toBean(dataJson, JSONConfig.create(), SettingEntity.class);
            WaveMap = entity.getWaveMap();
        } catch (IOException e) {
            log.error("波形数据加载失败");
        }
    }

    public static String getDataJson() throws IOException {
        try (InputStream jsonInput = new FileInputStream(HomePath + ConfigPath)) {
            byte[] bytes = IoUtil.readBytes(jsonInput);
            jsonInput.close();
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (FileNotFoundException e) {
            initDataJson(HomePath + ConfigPath);
            return getDataJson();
        }
    }

    private static void initDataJson(String initPath) throws IOException {
        SettingEntity setting = new SettingEntity();
        setting.setHomeJobList(new ArrayList<>());
        setting.setTriggerInterval(1);
        String dataJson = JSONUtil.toJsonStr(setting);
        //检查文件夹
        String paperFilePath = initPath.replace("\\setting.json", "");
        File paperFile = new File(paperFilePath);
        if (!paperFile.exists()) {
            boolean mkdirs = paperFile.mkdirs();
            log.info("初始化目录创建状态:{}", mkdirs);
        }
        //创建文件
        File file = new File(initPath);
        //写入数据
        if (file.createNewFile()) {
            FileWriter fileWriter = new FileWriter(initPath, true);
            fileWriter.write(dataJson);
            fileWriter.close();
        }
    }

    public static void upDateDataBaseJson(SettingEntity data) throws IOException {
        /**
         * @see HomeView#initialize() 请看133行注释 我很不理解
         */
        SettingEntityJson json = BeanUtil.copyProperties(data, SettingEntityJson.class);
        List<JobEntity> homeJobList = data.getHomeJobList();
        List<JobEntityJson> jobJSon = new ArrayList<>();
        homeJobList.forEach(entity -> {
            JobEntityJson es = BeanUtil.copyProperties(entity, JobEntityJson.class);
            es.setId(entity.getId());
            es.setListener(entity.getListener());
            es.setJobMethod(entity.getJobMethod());
            es.setCallback(entity.getCallback());
            es.setRemark(entity.getRemark());
            jobJSon.add(es);
        });
        json.setHomeJobList(jobJSon);

        String updateJsonStr = JSONUtil.toJsonStr(json);
        File file = new File(HomePath + ConfigPath);
        //写入数据
        if (!file.createNewFile()) {
            FileWriter fileWriter = new FileWriter(HomePath + ConfigPath);
            fileWriter.write(updateJsonStr);
            fileWriter.close();
        }

        //刷新波形数据
        refreshWave();

    }
}
